/*异步日志的缓冲区*/
#pragma once
#include <vector>
namespace viclog
{
#define DEFAULT_BUFFER_SIZE (100 * 1024 * 1024)
#define THRESHOLD_BUFFER_SIZE (80*1024*1024)
#define INCREMENT_BUFFER_SIZE (10*1024*1024)
    class Buffer
    {
    public:
        Buffer():_buffer(DEFAULT_BUFFER_SIZE),_reader_idx(0),_writer_idx(0) {}
        // 向缓冲区写
        void push(const char *data, size_t len)
        {
            //1.缓冲器剩余空间是否满足
            //1（1）固定大小 超过直接返回
            // if(len>writeAbleSize()) return ;
            //1（2）动态空间 不够扩容(用于极限测试)
            ensureEnoughSize(len);
            //2.数据拷贝到缓冲区
            std::copy(data,data+len,&_buffer[_writer_idx]);
            //3.写入位置向后偏移
            moveWriter(len);
        }
        // 获取可读数据的起始地址
        const char *begin()
        {
            return &_buffer[_reader_idx];
        }
        // 获取可读数据的长度
        size_t readAbleSize()
        {
            return (_writer_idx-_reader_idx);
        }
        // 获取可写数据的长度
        size_t writeAbleSize()
        {
            //针对固定大小缓冲区提供的接口
            return (_buffer.size()-_writer_idx);
        }
        // 移动读写位置(读写指针向后偏移)

        void moveReader(size_t len)
        {
            assert(len<=readAbleSize());
            _reader_idx+=len;
        }
        // 初始化缓冲区 重置读写位置
        void reset()
        {
            _writer_idx=0;
            _reader_idx=0;
        }
        // 交换缓冲区
        void swap( Buffer &buffer)
        {
            _buffer.swap(buffer._buffer);
            std::swap(_reader_idx,buffer._reader_idx);
            std::swap(_writer_idx,buffer._writer_idx);


        }
        // 判断缓冲区是否为空
        bool empty()
        {
            return (_reader_idx==_writer_idx);
        }

    private:
        void moveWriter(size_t len)
        {
            assert(_writer_idx+len<=_buffer.size());
            _writer_idx+=len;
        }
        //扩容
        void ensureEnoughSize(size_t len)
        {
            if(len<=writeAbleSize()) return ;
            size_t new_size;
            //小于阈值翻倍
            if(_buffer.size()<THRESHOLD_BUFFER_SIZE)
            {
                new_size=_buffer.size()*2+len;
            }
            else//大于阈值线性
            {
                new_size=_buffer.size()+INCREMENT_BUFFER_SIZE+len;
            }
            _buffer.resize(new_size);
        }

    private:
        std::vector<char> _buffer;
        size_t _reader_idx; // 当前可读位置
        size_t _writer_idx; // 当前可写位置
    };
}